from application import db
from common.libs import Helper
from common.libs.Restful import Restful
from common.libs.UrlManager import UrlManager
from common.models.foods.Food import Food
from common.models.members.MemberCart import MemberCart


class CartService(object):

    @staticmethod
    def cartList(member_id=0):
        if member_id < 1:
            return False
        cart_list = db.session.query(MemberCart).filter_by(member_id=member_id).all()
        data_cart_list = []
        if cart_list:
            food_ids = Helper.selectFilterObj(cart_list, 'food_id')
            food_map = Helper.getDictFilterField(Food, Food.id, 'id', food_ids)
            for item in cart_list:
                tmp_food_info = food_map[item.food_id]
                tmp_data = {
                    'id': item.id,
                    'food_id': item.food_id,
                    'number': item.quantity,
                    'name': tmp_food_info.name,
                    'price': str(tmp_food_info.price),
                    'url': UrlManager.buildImageUrl(tmp_food_info.main_image),
                    'active': True
                }
                data_cart_list.append(tmp_data)
            return data_cart_list
        return []

    @staticmethod
    def setItems(member_id=0, food_id=0, number=0):
        if member_id<1 or food_id<1 or number<1:
            return False
        cart_info = db.session.query(MemberCart).filter_by(food_id=food_id, member_id=member_id).first()
        if cart_info:
            cart_info.food_id = food_id
            cart_info.quantity = number
            cart_info.updated_time = Helper.geneDatetime()
            db.session.commit()
        else:
            model_cart = MemberCart()
            model_cart.member_id = member_id
            model_cart.created_time = Helper.geneDatetime()
            model_cart.food_id = food_id
            model_cart.quantity = number
            model_cart.updated_time = Helper.geneDatetime()
            db.session.add(model_cart)
            db.session.commit()
        return True


    @staticmethod
    def deleteItem(member_id=0, items=None):
        if member_id < 1 or not items:
            return False
        for item in items:
            db.session.query(MemberCart).filter_by(food_id=item['id'], member_id=member_id).delete()
        db.session.commit()
        return True












